<?php
/**
 * @name: router.class.php
 * @version: 1.0
 * @package: PHP MVC Framework
 * @uses: Handles site redirection
 * @copyright: MIT
 * @author Andrew Lowther
 */

class Router {

    /**
     * @var $registry
     * @type private
     * @return mixed
     */
    private $registry;

    /**
     * @var $path, $args, $file, $controller, $action
     * @type mixed
     * @usage Handles controller paths
     */
    private $path;
    private $args = array();

    public $file;
    public $controller;
    public $action;

    /**
     * @method __construct
     * @return mixed
     */
    public function __construct($registry) {

        $this->registry = $registry;

    }

    /**
     * @set controller directory path
     * @param string $path
     * @return void
     */
    public function setPath($path) {

        // Check if the path is a directory
        if (is_dir($path) == false) {

            throw new Exception('Invalid controller path: ' . $path);

        } else {

            $this->path = $path;

        }

    }

    /**
     * @load the controller
     * @access public
     * @return void
     */
    public function loader() {

        // Check the route
        $this->getController();

        // If the file is not there, die
        if (is_readable($this->file) == false) {

            die ('<h2>Controller not found!</h2>');

        }

        // Include the controller
        include $this->file;

        // Create a new controller class instance
        $class = $this->controller . 'Controller';
        $controller = new $class($this->registry);

        // Check if the action is available
        if (is_callable(array($controller, $this->action)) == false) {

            die('<h2>Action not found!</h2>');

        } else {

            $action = $this->action;

        }

        // Run the action
        $controller->$action();

    }

    /**
     * @get the controller
     * @access private
     * @return void
     */
    private function getController() {

        // Get the route from the url
        $route = (empty($_GET['rt'])) ? '' : $_GET['rt'];

        if (empty($route)) {

            $route = 'index';

        } else {

            // Get the parts of the route
            $parts = explode('/', $route);
            $this->controller = $parts[0];

            if (isset($parts[1])) {

                $this->action = $parts[1];

            }

        }

        if (empty($this->controller)) {

            $this->controller = 'index';

        }

        // Get the action
        if (empty($this->action)) {

            $this->action = 'index';

        }

        // Set the file path
        $this->file = $this->path . '/' . $this->controller . 'Controller.class.php';

    }

}

?>
